package httphandler

import (
	"context"
	_wpservice "github.com/romapres2010/goapp/pkg/common/workerpoolservice"

	_ctx "github.com/romapres2010/goapp/pkg/common/ctx"
	_err "github.com/romapres2010/goapp/pkg/common/error"
	_http "github.com/romapres2010/goapp/pkg/common/httpservice"
	_log "github.com/romapres2010/goapp/pkg/common/logger"
)

// Service represent HTTP service
type Service struct {
	ctx    context.Context    // 服务初始化时的根上下文
	cancel context.CancelFunc // 关闭全局上下文的函数
	cfg    *Config            // 配置参数

	// 嵌套服务
	httpService *_http.Service      // HTTP服务
	wpService   *_wpservice.Service // 工作池服务
}

// Config represent HTTP Service configurations
type Config struct {
}

// New create new HTTP service
func New(ctx context.Context, cfg *Config,
	wpService *_wpservice.Service,
	httpService *_http.Service) (*Service, error) {

	requestID := _ctx.FromContextHTTPRequestID(ctx) // RequestID 通过上下文传递

	_log.Info("Creating new HTTP service")

	{ // 输入检查
		if cfg == nil {
			return nil, _err.NewTyped(_err.ERR_INCORRECT_CALL_ERROR, requestID, "if cfg == nil {}").PrintfError()
		}
		if httpService == nil {
			return nil, _err.NewTyped(_err.ERR_INCORRECT_CALL_ERROR, requestID, "if httpService == nil {}").PrintfError()
		}
		if wpService == nil {
			return nil, _err.NewTyped(_err.ERR_INCORRECT_CALL_ERROR, requestID, "if wpService == nil {}").PrintfError()
		}
	} // 输入检查

	service := &Service{
		cfg:         cfg,
		wpService:   wpService,
		httpService: httpService,
	}

	// 创建带有取消功能的上下文
	if ctx == nil {
		service.ctx, service.cancel = context.WithCancel(context.Background())
	} else {
		service.ctx, service.cancel = context.WithCancel(ctx)
	}

	_log.Info("HTTP service was created")
	return service, nil
}
